﻿// This software is the confidential and proprietary information of NetBay.
// Such confidential information should not be disclosed.
// NetBay copyright(c) 2012

using System;
using System.Linq;
using System.Text;
using NetBay.Core.BusinessEntities;
using Rio.Applications.Web.Services;
using Rio.Framework.Pages.AppCode.ApplicationNavigation;
using Rio.Framework.Pages.Context;
using Rio.Framework.Pages.Enums;
using Rio.Framework.WCFService;

namespace Rio.Framework.Pages.Manager
{
    public class LoginManager
    {
        #region Events

        public event EventHandler AuthenticatedUser;
        public event EventHandler AuthenticatedUserFailed;

        #endregion

        #region Fields

        private static LoginManager _instance;

        #endregion

        #region Properties

        public LoginDomainServiceEnums.AuthenticationMethod AuthenticationMethod { get; private set; }
        public User CurrentUser { get; set; }
        public Uri LoginPageUri { get; private set; }
        public bool IsAuthenticated { get; private set; }

        public static LoginManager Instance
        {
            get
            {
                if (_instance == null)
                    _instance = new LoginManager();
                return _instance;
            }
        }

        #endregion

        #region Constructors

        private LoginManager()
        {
            AuthenticationMethod =
                (LoginDomainServiceEnums.AuthenticationMethod)
                Enum.ToObject(typeof (LoginDomainServiceEnums.AuthenticationMethod),
                              Int32.Parse(GlobalWebContext.RioAppSettings["AuthenticationMode"]));

            byte[] encodedLoginPage = Convert.FromBase64String(GlobalWebContext.RioAppSettings["LoginPage"]);

            LoginPageUri = new Uri(Encoding.Unicode.GetString(encodedLoginPage, 0, encodedLoginPage.Length));
        }

        #endregion

        public void LogOut()
        {
            BusinessEntitiesDomainContext ds = new BusinessEntitiesDomainContext();
            ds.Disconnect(e =>
                              {
                                  SetUser(null);
                                  NavigationHelper.Instance.NavigateToApplication(ApplicationName.RioOffice);
                              },
                          null);
        }

        /// <summary>
        ///   Sets the user [USED ONLY IN OLD WEB MANAGER - REMOVE IT IN 5.3]
        /// </summary>
        /// <param name = "currentUser">The current user.</param>
        public void SetUser(User currentUser)
        {
            Instance.CurrentUser = currentUser;

            ServiceManager.LicenseKey = currentUser == null ? null : currentUser.LicenseKey;

            Instance.IsAuthenticated = true;
        }

        public void LogUser(string login, string password)
        {
            BusinessEntitiesDomainContext ds = GlobalWebContext.BusinessEntitiesDomainContext;
            var getAccessQuery = ds.GetAccessQuery(
                login,
                password,
                (int) AuthenticationMethod,
                true);

            ds.Load(
                getAccessQuery,
                result =>
                    {
                        if (result.Entities != null && result.Entities.Count() > 0
                            && result.Entities.First().IsValid)
                        {
                            CurrentUser = result.Entities.First();
                            ServiceManager.LicenseKey = CurrentUser.LicenseKey;

                            OnAuthenticatedUser();
                        }
                        else
                        {
                            OnAuthenticatedUserFailed();
                        }
                    },
                null);
        }

        public void OnAuthenticatedUser()
        {
            if (AuthenticatedUser != null)
            {
                AuthenticatedUser(this, new EventArgs());
            }
        }

        public void OnAuthenticatedUserFailed()
        {
            if (AuthenticatedUserFailed != null)
            {
                AuthenticatedUserFailed(this, new EventArgs());
            }
        }
    }
}